﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace btnet.pages
{
    public partial class delete_customfield : CommonPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Bug_Util.do_not_cache(Response);

            security = new Security();
            security.check_security(HttpContext.Current, Security.MUST_BE_ADMIN);

            titl.Text = Bug_Util.get_setting("AppTitle", "BugTracker.NET") + " - "
                + "delete custom field";

            if (IsPostBack)
            {
                // do delete here

                sql = @"select sc.name [column_name], df.name [default_constraint_name]
			from syscolumns sc
			inner join sysobjects so on sc.id = so.id
			left outer join sysobjects df on df.id = sc.cdefault
			where so.name = 'bugs'
			and sc.colorder = $id";

                sql = sql.Replace("$id", row_id.Value);
                DataRow dr = DbUtil.get_datarow(sql);

                // if there is a default, delete it
                if (dr["default_constraint_name"].ToString() != "")
                {
                    sql = @"alter table bugs drop constraint [$df]";
                    sql = sql.Replace("$df", (string)dr["default_constraint_name"]);
                    DbUtil.execute_nonquery(sql);
                }


                // delete column itself
                sql = @"
alter table orgs drop column [og_$nm_field_permission_level]
alter table bugs drop column [$nm]";

                sql = sql.Replace("$nm", (string)dr["column_name"]);
                DbUtil.execute_nonquery(sql);


                //delete row from custom column table
                sql = @"delete from custom_col_metadata
		where ccm_colorder = $num";
                sql = sql.Replace("$num", row_id.Value);

                Application["custom_columns_dataset"] = null;
                DbUtil.execute_nonquery(sql);

                Response.Redirect("customfields.aspx");


            }
            else
            {
                string id = Bug_Util.sanitize_integer(Request["id"]);

                sql = @"select sc.name
			from syscolumns sc
			inner join sysobjects so on sc.id = so.id
			left outer join sysobjects df on df.id = sc.cdefault
			where so.name = 'bugs'
			and sc.colorder = $id";

                sql = sql.Replace("$id", id);
                DataRow dr = DbUtil.get_datarow(sql);

                confirm_href.InnerText = "confirm delete of \""
                    + Convert.ToString(dr["name"])
                    + "\"";

                row_id.Value = id;
            }
        }
    }
}
